package com.wangp.enjoywork.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.wangp.enjoywork.entity.SeaMan;

@Service
public class GeneratorExcelService {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private DeleteFileService deleteFileService ;
	

	//生成会签单
	public void generatorSignSummury(HttpServletRequest request, SeaMan seaMan, String baseName)
			throws IOException {
		InputStream in = GeneratorExcelService.class.getResourceAsStream("/船员调动汇签表.xls");
//		System.out.println("获取船员调动汇签表.xls原件" + "完毕！");
		logger.info("获取船员调动汇签表.xls原件完毕！开始注入参数");
		
		HSSFWorkbook workbook = new HSSFWorkbook(in);
		HSSFSheet sheet = workbook.getSheetAt(0);

		// 设定船舶名称
		HSSFRow row2 = sheet.getRow(2);
		HSSFCell cell2_1 = row2.getCell(1);
		cell2_1.setCellValue(seaMan.getShip_name());

		// 设定船舶名称
		HSSFCell cell2_4 = row2.getCell(4);
		cell2_4.setCellValue(seaMan.getLevel());

		// 設定上船船員姓名
		HSSFRow row4 = sheet.getRow(4);
		HSSFCell cell4_1 = row4.getCell(1);
		cell4_1.setCellValue(seaMan.getSign_on_name());

		// 设定上船船员生日
		HSSFCell cell4_4 = row4.getCell(4);
		cell4_4.setCellValue(seaMan.getSign_on_birth());

		// 设定上船日期
		HSSFRow row5 = sheet.getRow(5);
		HSSFCell cell5_1 = row5.getCell(1);
		cell5_1.setCellValue(seaMan.getSign_on_timeForOn());

		// 设定下船船员姓名
		HSSFRow row9 = sheet.getRow(9);
		HSSFCell cell9_1 = row9.getCell(1);
		cell9_1.setCellValue(seaMan.getSign_off_name());

		// 设定下船船员生日
		HSSFCell cell9_4 = row9.getCell(4);
		cell9_4.setCellValue(seaMan.getSign_off_birth());

		// 设定下船船员上船日期
		HSSFRow row10 = sheet.getRow(10);
		HSSFCell cell10_1 = row10.getCell(1);
		cell10_1.setCellValue(seaMan.getSign_off_timeForOn());
		
//		System.out.println("船员调动汇签表.xls设定" + "完毕！");
		logger.info("船员调动汇签表.xls的参数注入完毕，即将开始保存至服务器");
		
		String excelName = baseName + ".xls";
		String path = request.getSession().getServletContext().getRealPath(excelName);
		workbook.write(new File(path));
		
//		System.out.println("船员调动汇签表.xls保存至服务器" + "完毕！");
		logger.info("船员调动汇签表.xls已保存至服务器，路径为：{}",path);

		request.setAttribute("signsummary", excelName);

		workbook.close();
		
		deleteFileService.deleteFile(path);

	}
	
	
	
	public void saveSignOnCrewResume(HttpServletRequest request, MultipartFile sign_on,String baseName)
			throws IOException {
		
		logger.info("读取上船人员简历表，即将保存至服务器");

		FileInputStream fis = (FileInputStream) sign_on.getInputStream();
		
		HSSFWorkbook SignOnCrewResume = new HSSFWorkbook(fis);


		String SignOnCrewResumePath = baseName +"-16"+ ".xls";
		String path = request.getSession().getServletContext().getRealPath(SignOnCrewResumePath);
		
		SignOnCrewResume.write(new File(path));

		request.setAttribute("crewresume", SignOnCrewResumePath);

		SignOnCrewResume.close();
		
		logger.info("上船人员简历表已保存至服务器，路径为：{}",path);
		
//		System.out.println(path);
//		logger.info("客户请求的所有文件保存完毕，路径为：{}" ,path);
		
		deleteFileService.deleteFile(path);
		
	}

	// 生成资格评定表
	public void generatorQualifyWord(HttpServletRequest request, SeaMan seaMan, String baseName)
			throws IOException {
		
		logger.info("开始生成资格评定表");
		
		String level = seaMan.getLevel();
		InputStream in;
		HWPFDocument doc;
		if ("船长".equals(level)) {
			in = GeneratorExcelService.class.getResourceAsStream("/SMI-0602-02 R-02 船长任职资格评定表.doc");
			logger.info("读取<{}资格评定表>成功",level);
		} else if ("大副".equals(level) || "二副".equals(level) || "三副".equals(level)) {
			in = GeneratorExcelService.class.getResourceAsStream("/SMI-0602-02 R-03 甲板部高级船员资格评定表.doc");
			logger.info("读取<{}资格评定表>成功",level);
		} else {
			in = GeneratorExcelService.class.getResourceAsStream("/SMI-0602-02 R-05 普通船员资格评定表.doc");
			logger.info("读取<{}资格评定表>成功",level);
		}

		logger.info("开始向资格评定表中注入参数");
		
		doc = new HWPFDocument(in);

		 Range range =doc.getRange();
		 TableIterator it=new TableIterator(range);
		 it.hasNext();
		 Table tb=(Table)it.next();
		
		 //设定姓名
		 TableRow tr1=tb.getRow(1);
		 TableCell td1_0=tr1.getCell(0);
		 td1_0.insertBefore(seaMan.getSign_on_name());
		
		 //设定职务
		 TableCell td1_1=tr1.getCell(1);
		 td1_1.insertBefore(seaMan.getLevel());
		
		 //设定生日
		 TableCell td1_2=tr1.getCell(2);
		 td1_2.insertBefore(seaMan.getSign_on_birth());
		
		 //设定电话号码
		 TableCell td1_3=tr1.getCell(3);
		 td1_3.insertBefore(seaMan.getSign_on_phone());
		
		 //设定资料是否齐全
		 TableRow tr2=tb.getRow(2);
		 TableCell td2_1=tr2.getCell(1);
		 td2_1.replaceText("齐全 （√） 短缺（  ）:1.        2.          3.          4 .          ",false);
		 
		 
		 //设定培训情况
//		 TableRow tr3=tb.getRow(3);
//		 TableCell td3_1=tr3.getCell(1);
//		 if (level.equals("船长")) {
//			 td3_1.replaceText("STCW 95 （√）， ISM （√）， GMDSS （√）， ARPA （√）",false);
//		 } else if (level.equals("大副") || level.equals("二副") || level.equals("三副")) {
//			 td3_1.replaceText("STCW 95 （√）， ISM （√）， GMDSS （√）， ARPA （√）",false);
//		 } else {
//			 td3_1.replaceText("STCW 95 （√）",false);
//		 }
		 
		 //设定资历情况
		 TableRow tr3=tb.getRow(3);
		 TableCell td3_2=tr3.getCell(2);
		 if (level.equals("实习生")) {
			 td3_2.replaceText("新聘实习生，证书齐全",false);
		 } else {
			 td3_2.replaceText("有船舶服务资历，证书齐全",false);
		 }
		 
		logger.info("资格评定表参数注入完毕,准备保存至服务器");
		 
		 String wordName = baseName + ".doc";
		 String path = request.getSession().getServletContext().getRealPath(wordName);
		 doc.write(new File(path));
		 
		 logger.info("资格评定保存至服务器完毕，路径为：{}",path);

		 request.setAttribute("qualifyword", wordName);
		 
//		try {
//			String[] s = new String[20];
//			Range range = doc.getRange();
//			TableIterator it = new TableIterator(range);
//			int index = 0;
//			while (it.hasNext()) {
//				Table tb = (Table) it.next();
//				for (int i = 0; i < tb.numRows(); i++) {
//					System.out.println("Numrows :" + tb.numRows());
//					System.out.println("第" + i + "行");
//					TableRow tr = tb.getRow(i);
//					for (int j = 0; j < tr.numCells(); j++) {
//						System.out.println("numCells :" + tr.numCells());
//						System.out.println("j :" + j);
//						TableCell td = tr.getCell(j);
//						System.out.println(td.text().trim());
//					}
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		doc.close();
		
	
		
		deleteFileService.deleteFile(path);

	}
}
